import React, {useState, useRef, useEffect} from 'react';
import styles from './index.css'
import testStyles from "./test.less"
import {isEmpty} from "lodash";



export default function App() {  // 默认导出
    // 找到所有满足条件的 {{}} 起始与结束索引
const inputRef = useRef(null);
// 输入函数
    const handleInputChange =(e)=>{
        const parentNode = inputRef.current;
        const innerVal = e?.target?.innerText;
        const regex = /\{\{(.*?)\}\}/g;
        const se = window.getSelection();
        const {anchorNode,focusOffset} = se
        const rag = se.getRangeAt(0);
        const co = rag.commonAncestorContainer;
        let match;
        while((match = regex.exec(co.textContent))!=null&&co.nodeType===Node.TEXT_NODE&&co.tagName!=='SPAN'){
            const startIndex = match.index;
            const endIndex = match.index+match[0]?.length;
            if(startIndex<focusOffset&&focusOffset<endIndex)return
            // 移除不需要的文本节点 替换成span
            rag.setStart(co,startIndex)
            rag.setEnd(co,endIndex)
            rag.deleteContents();
            // 创建一个span
            const spanNode = document.createElement("span");
            spanNode.innerText = match[0];
            spanNode.style.color="red";
            spanNode.setAttribute('contenteditable',true)
            rag.insertNode(spanNode)
            rag.setStartBefore(spanNode);
            rag.collapse(true)
            const emptyNodeBefore =document.createElement('i');
            emptyNodeBefore.innerText='2';
            emptyNodeBefore.setAttribute('contenteditable',false);
            emptyNodeBefore.setAttribute('tempStr',true);
            rag.insertNode(emptyNodeBefore);
            rag.setStartAfter(spanNode);
            const emptyNodeAfter =document.createElement('i');
            emptyNodeAfter.innerText='1';
            emptyNodeAfter.setAttribute('contenteditable',false);
            emptyNodeAfter.setAttribute('tempStr',true);
            rag.insertNode(emptyNodeAfter);
            rag.setStartAfter(emptyNodeAfter);

            rag.setStartAfter(emptyNodeAfter)
        }




    }
useEffect(()=>{
    if(inputRef.current){
        inputRef.current.addEventListener("input", handleInputChange)
    }
})

    return <>
        <div contenteditable="true" ref={inputRef} className={styles.inputRef}></div>
    </>;
}
